package com.regiee.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.regiee.dto.DishDto;
import com.regiee.entity.Category;
import com.regiee.entity.Dish;
import com.regiee.entity.DishFlavor;
import com.regiee.mapper.DishMapper;
import com.regiee.service.CategoryService;
import com.regiee.service.DishFlavorService;
import com.regiee.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    //新增菜品，同时插入菜品对应的口味数据，需要操作两张表：dish，dish_flavor
    @Override
    @Transactional
    public void saveFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表dish
        this.save(dishDto);
        Long dishId=dishDto.getId();//菜品Id
        List<DishFlavor> list=dishDto.getFlavors();
        for(DishFlavor dishFlavor:list){
            dishFlavor.setDishId(dishId);
        }
        dishFlavorService.saveBatch(list);
        //保存菜品口味数据到菜品口味表dish_flavor
    }
    //根据菜品Id来查询菜品信息和口味信息
    @Override
    @Transactional
    public DishDto getByFlavor(Long id) {
        DishFlavor dishFlavor=new DishFlavor();
        DishDto dishDto=new DishDto();
     //查询菜品基本信息，从dish表查询
       Dish dish= this.getById(id);
        // 查询菜品口味表信息，丛dish_flavor中查询
        LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper<DishFlavor>()
                .eq(DishFlavor::getDishId,id);
        List<DishFlavor> list=dishFlavorService.list(wrapper);
        dishDto.setFlavors(list);
        BeanUtils.copyProperties(dish,dishDto);
        return dishDto;
    }

    @Override
    @Transactional
    public void uodateFlavor(DishDto dishDto) {
        //修改菜品信息
        this.updateById(dishDto);//修改菜品的基本信息
        //清理dish_flavor中的数据
        LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper<DishFlavor>()
                .eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wrapper);
        //修改菜品口味信息
        Long dishId=dishDto.getId();//菜品Id
        List<DishFlavor> list=dishDto.getFlavors();
        for(DishFlavor dishFlavor:list){
            dishFlavor.setDishId(dishId);
        }
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }
}
